package com.boot2.core.web.websocket;

import com.boot2.core.expiringmap.ExpiringMap;
import com.boot2.core.utils.EnvironmentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangweilin
 * @Description: xxxxx
 * @date 2020/12/14
 */
@Component
@Slf4j
public class WebSocketSessionManager {

    private ExpiringMap<String, Boolean> map = null;

    @Autowired(required = false)
    WebSocketSessionListener webSocketSessionListener;


    @PostConstruct
    public void init() {
        Integer expiration = getExpiration();
        map = ExpiringMap.builder()
                .expiration(expiration, TimeUnit.SECONDS)
                .variableExpiration()
                .expirationListener((k, v) -> {
                    doOffline((String) k);
                }).build();
    }

    public void setExpiration(long duration, TimeUnit timeUnit) {
        map.setExpiration(duration, timeUnit);
    }

    public void online(String userName, long duration, TimeUnit timeUnit) {
        map.put(userName, true);
        map.setExpiration(userName, duration, timeUnit);
        if (null != webSocketSessionListener) {
            webSocketSessionListener.online(userName);
        }
    }

    /**
     * 默认是60s有效期
     *
     * @param userName
     */
    public void online(String userName) {
        Integer expiration = getExpiration();
        online(userName, expiration, TimeUnit.SECONDS);
        if (null != webSocketSessionListener) {
            webSocketSessionListener.online(userName);
        }
    }

    public void offline(String userName) {
        map.remove(userName);
        doOffline(userName);
    }

    private void doOffline(String userName) {
        if (null != webSocketSessionListener) {
            webSocketSessionListener.offline(userName);
        }
    }

    private Integer getExpiration() {
        return EnvironmentUtil.getInt("websocket.heart-beat.interval", 60+20);
    }
}
